from wtforms import StringField, PasswordField, Form
from wtforms.validators import DataRequired, Length, Email, ValidationError

from app.models.user import User


class RegisterForm(Form):
    nickname = StringField('昵称', validators=[
        DataRequired(), Length(2, 10, message='昵称至少需要两个字符，最多10个字符')])

    password = PasswordField('密码', validators=[
        DataRequired(message='昵称至少需要两个字符，最多10个字符'), Length(6, 32)])

    email = StringField(validators=[DataRequired(), Length(8, 64), Email(message='电子邮件不符合规范')])

    def validate_email(self, field):
        # db.session.
        # User.query.filter_by(email=field.data).first()
        # 等同于
        # select * from user where name = field.data limit 1
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('邮件已注册')

    def validate_nickname(self, field):
        if User.query.filter_by(nickname=field.data).first():
            raise ValidationError('昵称已存在')


class LoginForm(Form):
    password = PasswordField('密码', validators=[
        DataRequired(message='昵称至少需要两个字符，最多10个字符'), Length(6, 32)])

    email = StringField(validators=[DataRequired(), Length(8, 64), Email(message='电子邮件不符合规范')])
